//
//  LTAppDelegate.m
//  LocalTravelIPhone
//
//  Created by zheng ji on 14-3-28.
//  Copyright (c) 2014年 jxw. All rights reserved.
//

#import "LTAppDelegate.h"
@interface LTAppDelegate ()
{
    NSArray* _provinceArrayData;
      NSDictionary *_pushPayload;
      NSUserDefaults *myDefaults;
    AppDelegateAttachment* appAttachement;
}
@end
@implementation LTAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [self initApp:launchOptions];
   
    
    return YES;
    
    
}



- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
-(void)initApp:(NSDictionary*)dict{
    
    self.currentPostionlatitude=0.0;
    self.currentPostionlongitude=0.0;
    self.currentCityID=@"";
    self.currentCityName=@"";
    myDefaults=[NSUserDefaults standardUserDefaults];
    appAttachement=[[AppDelegateAttachment alloc]init];
    [appAttachement umengStartup];
    
    [appAttachement createLocalDirectory];
    
    [appAttachement registerForRemoteNotification];
   
    
    [appAttachement addMobileUser];
    
    [appAttachement parseLaunchingOptions:dict];
    
}


- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    if(nil!=deviceToken) {
        NSMutableString *strdeviceToken = [[NSMutableString alloc] initWithFormat:@"%@",deviceToken];
        if(nil!=strdeviceToken){
            
            
            
            [myDefaults setObject:strdeviceToken forKey:@"deviceToken"];
            [myDefaults synchronize];
            
            
            
            
            strdeviceToken=nil;
            
        }
        
        
    }
    [appAttachement addMobileUser];
   // [NSThread detachNewThreadSelector:@selector(addMobileUser:) toTarget:self withObject:@"Y"];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    // NSLog(@"error:%@",error);
    // [NSThread detachNewThreadSelector:@selector(addMobileUser) toTarget:self withObject:nil];
}


/**
 接受到远程通知
 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    
    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    
    NSDictionary *aps=[userInfo objectForKey:@"aps"];
    NSString *alertMessage=[aps objectForKey:@"alert"];
    if(nil!=alertMessage){
        
        NSString *advtype =[userInfo objectForKey:@"t"];//advtype
        NSString *objectid =[userInfo objectForKey:@"i"];
        NSString *objectname =[userInfo objectForKey:@"n"];
        NSString *batchId =[userInfo objectForKey:@"b"];//批量
        
        
        if(nil==advtype)advtype=@"";
        if(nil==objectid)objectid=@"";
        if(nil==objectname)objectname=@"";
        if(nil==batchId)batchId=@"";
        
        
        _pushPayload=[NSDictionary dictionaryWithObjectsAndKeys:advtype,@"advtype",@"",@"name",objectid,@"objectId",objectname,@"objectName",alertMessage,@"title",batchId,@"batchid",nil];
        
        [appAttachement savePushMsgLog:_pushPayload];
        
     
        [appAttachement parseLaunchingOptions:_pushPayload];
        
        
        
        
    }
    
    
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    //评分
    if([alertView tag]==998 && buttonIndex == 1 ) {
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[CommonConfigUtil getAppStoreCommentUrl]]];
    }
    else if([alertView tag]==999 && buttonIndex == 1 ) {
        // [self toShare];
    }
    
    else if([alertView tag]==1000 && buttonIndex == 1 ) {
        
        if( nil!=_pushPayload){
            [appAttachement pushMessageWithParams:_pushPayload];
        }
    }
    
    
}

-(NSString*) getCityIDByName:(NSString*)cityName{
    if (_provinceArrayData==nil) {
        [self getProvinceData];
    }
    NSString* cityID=@"";
    BOOL isFind=NO;
    for (NSDictionary* dictProvince in _provinceArrayData) {
        if(isFind) break;
        
        NSDictionary* dictCityList=[dictProvince objectForKey:@"cityList"];
        NSObject* obj=[dictCityList objectForKey:@"city"];
        if([obj isKindOfClass:[NSDictionary class]]){
            NSDictionary* d =[dictCityList objectForKey:@"city"];
            NSString* name=[d objectForKey:@"name"];
            if([name isEqualToString:cityName]){
                cityID=[d objectForKey:@"id"];
                isFind=YES;
            }
        }else if([obj isKindOfClass:[NSArray class]]){
            NSArray* array=[dictCityList objectForKey:@"city"];
            
            for (NSDictionary* dictCity in array) {
                NSString* name=[dictCity objectForKey:@"name"];
                if([name isEqualToString:cityName]){
                    cityID=[dictCity objectForKey:@"id"];
                    isFind=YES;
                    break;
                }
                
            }
            
        }
        
        
        
    }
    
    return cityID;
}
-(NSArray*) getProvinceData{
    if(_provinceArrayData==nil){
        
        NSString* file=[[NSBundle mainBundle] pathForResource:@"citys" ofType:@"json"];
        NSError* error=nil;
        NSDictionary *dictionary= [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:file] options:kNilOptions error:&error];
        if(!error){
            
            
            NSDictionary *dict=[dictionary objectForKey:@"provincelist"];
            if(dict !=nil && dict.count>0){
                _provinceArrayData=[dict objectForKey:@"province"];
                
            }
            
            
        }
    }
    return _provinceArrayData;
    
}


@end
